package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @PACKAGE_NAME: com.atguigu.config
 * @CLASSNAME: MyUserDetailService
 * @AUTHOR: zhangsan
 * @DATE: 2024/5/4 17:30
 * @SINCE 17.0.7
 * @DESCRIPTION: MyUserDetailService
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    @Reference
    private AdminService adminService;

    @Reference
    private PermissionService permissionService;

    /**
     * @param username the username identifying the user whose data is required.
     *                 用户在登录页面输入的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("username ------> " + username);
        Admin admin = adminService.getByUsername(username);
        if (null == admin) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        //用户功能权限
        List<String> codeList = permissionService.findCodeListByAdminId(admin.getId());
        Collection<GrantedAuthority> authorities = codeList.stream().filter(code -> !StringUtils.isEmpty(code)).map((Function<String, GrantedAuthority>) SimpleGrantedAuthority::new).collect(Collectors.toList());

        return new User(username, admin.getPassword(), authorities);
    }
}
